package linkedlist;

import java.util.ArrayList;
import java.util.List;

/**
 * 链表的定义以及相应的操作方法
 *
 * @author simon zhao
 */
public class ListNode {
    int val;

    public ListNode next;

    public ListNode(int val) {
        this.val = val;
    }

    /**
     * 根据数组生成LinkedList
     *
     * @param nums
     * @return
     */
    public static ListNode generateLinkedList(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        ListNode head = new ListNode(nums[0]);
        ListNode cur = head;
        for (int i = 1; i < nums.length; ++i) {
            ListNode node = new ListNode(nums[i]);
            cur.next = node;
            cur = node;
        }
        return head;
    }

    /**
     * 遍历LinkedList,返回一个List<Integer>
     *
     * @param head
     * @return
     */
    public static List<Integer> traverseLinkedList(ListNode head) {
        if (head == null) {
            return null;
        }
        List<Integer> traverse = new ArrayList<>();
        ListNode cur = head;
        while (cur != null) {
            traverse.add(cur.val);
            cur = cur.next;
        }
        return traverse;
    }

    /**
     * 返回LinkedList中index这个ListNode
     *
     * @param head
     * @param index
     * @return
     */
    public static ListNode getIndexNode(ListNode head, int index) {
        if (head == null) {
            return null;
        }
        int count = 0;
        ListNode cur = head;
        while (cur != null) {
            if (count == index) {
                return cur;
            }
            if (count < index) {
                count++;
                cur = cur.next;
            }
        }
        //如果LinkedList都已经遍历完毕，但是count依然小于index，说明index过大，超出了LinkedList的长度
        return null;
    }

    /**
     * 输出链表拼接字符串，示例：1->2->3
     *
     * @param head
     * @return
     */
    public static String toLinkedListString(ListNode head) {

        StringBuilder builder = new StringBuilder();

        String connector = "->";

        while (head != null) {
            builder.append(head.val);
            if (head.next != null) {
                builder.append(connector);
            }
            head = head.next;
        }

        return builder.toString();

    }
}
